<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <!--<TodoHeader v-on:addTodo="addTodo"/>-->
      <TodoHeader ref="header"/>
      <TodoList :todos="todos"/>
      <!--<TodoFooter :clearTodos="clearTodos" :todos="todos" :selectAllTodos="selectAllTodos"/>-->
      <todo-footer>
        <input slot="checkAll" type="checkbox" v-model="isAllCheck"/>
        <span slot="count">已完成{{completeSize}} / 全部{{todos.length}}</span>
        <button slot="delete" class="btn btn-danger" @click="clearTodos" v-show="completeSize">清除已完成任务</button>
      </todo-footer>
    </div>
  </div>
</template>

<script>
    import TodoHeader from './components/TodoHeader'
    import TodoList from './components/TodoList'
    import TodoFooter from './components/TodoFooter'
    import PubSub from 'pubsub-js'
    import storageUtil from './util/storageUtil'
    export default {
        name: "App",
        data(){
          return {
              /*todos:[
                {title:'刷牙',complete:false},
                {title:'早餐',complete:true},
                {title:'上班',complete:false}
              ]*/
              todos:storageUtil.readTodos()
          }
        },

        computed:{
          completeSize(){
            return this.todos.reduce((preTotal,todo)=>preTotal+(todo.complete?1:0),0)
          },
          isAllCheck:{
            get(){
              return this.completeSize===this.todos.length && this.completeSize>0;
            },
            set(value){
              this.selectAllTodos(value)
            }
          }
        },

        components: {
          TodoHeader,
          TodoList,
          TodoFooter
        },
        methods:{
          addTodo(todo){
            this.todos.unshift(todo)
          },
          delTodo(index){
            this.todos.splice(index,1);
          },
          clearTodos(){
            this.todos=this.todos.filter(todo=>!todo.complete);
          },
          selectAllTodos(check){
            this.todos.forEach(todo=>todo.complete=check);
          }
        },
        watch:{
          todos:{
            deep:true,
            handler:function (value) {
              //window.localStorage.setItem('todos_key',JSON.stringify(value))
              storageUtil.saveTodos(value)
            }
          }
        },
        mounted() {

          //给<TodoHeader/>绑定addTodo事件监听
          this.$refs.header.$on('addTodo',this.addTodo);

          //订阅消息
          PubSub.subscribe('delTodo', (msg,index) =>{
            this.delTodo(index);
          })
        }

    }
</script>

<style scoped>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>
